package ro.ubbcluj.adm.twitter.client;

import twitter4j.auth.AccessToken;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

/**
 * Class used to communicate with the Preferences Storage.
 */
public class PreferencesStorage {

	/**
	 * Keys used to store data into the Preferences storage.
	 */
	private static final String APPLICATION_PREFERENCES = "twitter_preferences";
	private static final String TWEET_AUTH_KEY = "auth_key";
	private static final String TWEET_AUTH_SEKRET_KEY = "auth_secret_key";

	/**
	 * Loads a saved AccessToken if exists.
	 * 
	 * @param context
	 * @return AccessToken if exists, null otherwise
	 */
	public static AccessToken loadAccessTokenFromPreferences(Context context) {
		SharedPreferences preferences = context.getSharedPreferences(APPLICATION_PREFERENCES, Context.MODE_PRIVATE);
		String token = preferences.getString(TWEET_AUTH_KEY, null);
		String tokenSecret = preferences.getString(TWEET_AUTH_SEKRET_KEY, null);
		if (null != token && null != tokenSecret) {
			return new AccessToken(token, tokenSecret);
		}
		return null;
	}

	/**
	 * Saves an AccessToken to storage as default user for the Twitter client.
	 * 
	 * @param context
	 * @param accessToken
	 */
	public static void storeAccessTokenToPreferences(Context context, AccessToken accessToken) {
		SharedPreferences preferences = context.getSharedPreferences(APPLICATION_PREFERENCES, Context.MODE_PRIVATE);
		Editor editor = preferences.edit();
		editor.putString(TWEET_AUTH_KEY, accessToken.getToken());
		editor.putString(TWEET_AUTH_SEKRET_KEY, accessToken.getTokenSecret());
		editor.commit();
	}

	/**
	 * Deletes the default AccessToken from storage. User will have to
	 * authenticate and authorize.
	 * 
	 * @param context
	 */
	public static void deleteAccessTokenToPreferences(Context context) {
		SharedPreferences preferences = context.getSharedPreferences(APPLICATION_PREFERENCES, Context.MODE_PRIVATE);
		Editor editor = preferences.edit();
		editor.clear();
		editor.commit();
	}
}
